<template>
  <div class="main-header">
    <el-card class="box-card" style="height: 300px;" shadow="never">
      <div slot="header" class="cardHeard" style="height: 38px">
        <div>
          <span class="title">授权信息</span>
        </div>
        <div>
          <el-button type="primary" title="修改设备ID" @click="save()">修改设备ID</el-button>
          <span style="display: inline-block;text-align: right;margin-left:10px;">
            <el-upload class="upload-demo" action :ref="'uploads' + 0" :on-change="handleChange()" :show-file-list=false
              :http-request="upgradeClick" :on-exceed="handleExceeds" :limit="1">
              <el-button type="primary" title="导入授权文件" @click="beforeUploadClick(0, '导入授权文件')">导入授权文件</el-button>
            </el-upload>
          </span>
          <!-- <el-button style="float: right; margin-left:5px;" type="primary" @click="confirmClick('authorizationInformation')">保存设置</el-button> -->
        </div>
      </div>
      <div>
        <el-form :model="authorizationInformation" ref="authorizationInformation" label-width="40%">
          <el-row :gutter="24">
            <div style="margin-bottom: 20px;">
              <div style="margin-bottom: 10px;">
                <span
                  style="width: 40%;display: inline-block;text-align: right;font-size: 14px; color:#606266;">设备ID：</span>
                <el-input v-model="authorizationInformation.CorpUUID" style="width: 100%;" size="small" maxlength="12"
                  oninput="value=value.replace(/[^0-9]/g,'')" ref="inputRef" readonly>
                  <!-- <el-button slot="append" icon="el-icon-check" @click="save" title="保存设备ID"></el-button> -->
                  <el-button slot="append" icon="el-icon-document-copy" @click="copy" title="复制设备ID"></el-button>
                </el-input>
              </div>
              <div style="margin-bottom: 10px;">
                <span
                  style="width: 40%;display: inline-block;text-align: right;font-size: 14px; color:#606266;">授权到期时间：</span>
                <el-input v-model="authorizationInformation.ValidTime" style="width:calc(100% - 300px);" size="small"
                  readonly></el-input>
                <span
                  :style="{ color: authorizationInformation.Days > 30 ? '#0ECB92' : '#FD8854', fontSize: '14px', marginLeft: '10px' }">授权{{ authorizationInformation.Days
                    < 0 ? '过期' : '剩余' }} {{ Math.abs(authorizationInformation.Days) || 0 }} 天</span>
              </div>
              <div style="margin-bottom: 10px;">
                <span
                  style="width: 40%;display: inline-block;text-align: right;font-size: 14px; color:#606266;">最多可以注册资产数量：</span>
                <el-input v-model="authorizationInformation.LicenseCount" style="width:calc(100% - 300px);" size="small"
                  readonly></el-input>
              </div>
              <div style="display:flex;align-item:center;margin-top:30px;justify-content: flex-end;">

              </div>
            </div>
          </el-row>
        </el-form>
      </div>
      <div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { connrequest, uploadfile } from "@/api/firstPage"
import { parseTime } from "@/utils/index.js";
import { getToken } from '@/utils/auth' // get token from cookie
export default {
  data() {
    return {
      authorizationInformation: {},
      applicationCode: '',
      authorizationCode: '',
    }
  },
  created() {
    this.getData();
  },
  methods: {
    // 获取邮件列表数据
    async getData() {
      const res = await connrequest('GetLicense');
      if (res.Status.StatusCode === 0) {
        this.authorizationInformation = { ...res.Data, ValidTime: parseTime(res.Data.ValidTime * 1000), Days: this.calculateDateAfterNdays(res.Data.ValidTime) }
      }
    },
    // 剩余天数
    calculateDateAfterNdays(ValidTime) {
      // 当前时间戳
      let currentTimestamp = (new Date()).getTime() / 1000;
      // 计算时间差并转换成天数
      let difference = Math.floor((ValidTime - currentTimestamp) / (60 * 60 * 24));
      return difference
    },
    handleChange(row) {
    },
    beforeUploadClick(index, val) {
      this.selectType = val
      this.slectIndex = index
    },
    handleExceeds(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async save() {
      this.$prompt('此操作将会更新设备ID，同时会清除已有的授权信息，需要重新授权，是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{12}$/, // 限制为12位数字
        inputErrorMessage: '设备ID格式不正确',
        inputPlaceholder: '请输入12位数字的设备ID'
      }).then(async ({ value }) => {
        const data = {
          Data: {
            UUID: value
          }
        }
        const res = await connrequest('SetDeviceUUID', data)
        if (res.Status.StatusCode === 0) {
          this.$message.success('保存成功')
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    copy() {
      // 选择输入框中的内容
      this.$refs.inputRef.select();
      // 复制选定的文本到剪贴板
      document.execCommand('copy');
      // 取消选择文本
      window.getSelection().removeAllRanges();
      this.$message.success('复制成功')
    },
    async upgradeClick(file) {
      // 导入授权文件
      const loading = this.$loading({
        lock: true,
        text: '导入授权文件中请稍后......',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (file.file.size > 102400000) {
        this.$refs['uploads' + this.slectIndex].clearFiles();
        setTimeout(() => {
          loading.close();
          this.$message.warning('文件大小不允许超过1KB');
        }, 1000);
      } else {
        let formData = new FormData();
        if (this.selectType === '导入授权文件') {
          var fileName = "param_license.cfg";
          // 创建一个新的Blob对象，将文件对象和文件名传入
          var newFile = new Blob([file.file], { type: file.file.type });
          newFile.name = fileName;
          formData.append('CmdCode', "UpdateLicense");
          formData.append('file', newFile, fileName);
          const res = await uploadfile(formData)
          if (res.Status.StatusCode === 0) {
            loading.close();
            this.$message.success('更新授权信息成功')
            this.$refs['uploads' + this.slectIndex].clearFiles();
            this.getData();
          } else {
            this.$refs['uploads' + this.slectIndex].clearFiles();
            setTimeout(() => {
              loading.close();
            }, 1000)
          }
        }
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.box-card {
  // margin: 16px;
  margin-bottom: 10px !important;
}

.cardHeard {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep .el-input--small {
  width: 40% !important;
}

::v-deep .el-card__header {
  padding: 10px !important;
}

.el-form-item {
  margin-bottom: 10px !important;
}

::v-deep .el-form-item__error {
  padding-top: 0 !important;
}</style>